package com.sjx.jnistudy.swallow;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

/**
 * Created by swallowsonny on 2016/11/24.
 * 嵌套listView 问题， 自定义控件的ViewHolder
 */

public class SwallowViewHolder {
    private SparseArray<View> mViews;
    private Context mContext;
    private View mConvertView;

    public SwallowViewHolder(Context context, View convertView) {
        mContext = context;
        mViews = new SparseArray<>();
        mConvertView = convertView;
    }

    /**
     * 通过viewId（控件的ID）来获取控件
     * @param viewId
     * @param <T>
     * @return
     */
    public <T extends View> T getView(int viewId) {
        View view = mViews.get(viewId);
        if (view == null) {
            view = mConvertView.findViewById(viewId);
            mViews.put(viewId, view);
        }
        return (T)view;
    }

    public View getConvertView() {
        return mConvertView;
    }

    public SwallowViewHolder setSelected(int viewId, boolean flag){
        View view = getView(viewId);
        view.setSelected(flag);
        return this;
    }

    /**-------------------------------设置值------------------------------------------**/
    public SwallowViewHolder setText(int viewId, CharSequence text){
        TextView tv = getView(viewId);
        tv.setText(text);
        return this;
    }

    public SwallowViewHolder setTextColor(int viewId, int resColorId){
        TextView tv = getView(viewId);
        tv.setTextColor(resColorId);
        return this;
    }

    public SwallowViewHolder setImageResource(int viewId, int resId) {
        ImageView view = getView(viewId);
        view.setImageResource(resId);
        return this;
    }

    public SwallowViewHolder setImageBitmap(int viewId, Bitmap bitmap){
        ImageView view = getView(viewId);
        view.setImageBitmap(bitmap);
        return this;
    }


    public SwallowViewHolder setVisible(int viewId, boolean visible) {
        View view = getView(viewId);
        view.setVisibility(visible ? View.VISIBLE : View.GONE);
        return this;
    }

    public SwallowViewHolder setHide(int viewId, boolean hide) {
        View view = getView(viewId);
        view.setVisibility(hide ? View.INVISIBLE : View.VISIBLE);
        return this;
    }
    public SwallowViewHolder setBackgroundResource(int viewId, int colorId){
        View view = getView(viewId);
        view.setBackgroundResource(colorId);
        return this;
    }



    /**--------------------------------事件-------------------------------------------**/
    public SwallowViewHolder setOnClickListener(int viewId, View.OnClickListener listener) {
        View view = getView(viewId);
        view.setOnClickListener(listener);
        return this;
    }
}
